﻿
//前端的js代码

window.onload = function () {


    var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();//新建连接

    connection.on("ReceiveMessage", function (user, time, message) {
        var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
        var encodedMsg = user + "  " + msg;
        //var li = document.createElement("li");
        //li.textContent = encodedMsg;\
        var li = "<li>\
            <p class='time-p'></p>\
             <p class='msg-p-rec'>" + message + "</p>\
            </li> ";
        document.getElementById("messagesList").innerHTML+=li;
    });


    connection.start().then(function () {
        document.getElementById("sendButton").disabled = false;
    }).catch(function (err) {
        return console.error(err.toString());
    });
    connection.on("OnConnected", function (message) {
        console.log(message);
    });

    connection.on("OnDisconnected", function (message) {
        console.log(message);
    });
    document.getElementById("sendButton").addEventListener("click", function (event) {
        var msg = document.getElementById("messageInput").value.trim();
        if (msg=="") {
            document.getElementById("messageInput").focus();
            return;
        }
        var user = "我";//document.getElementById("userInput").value;
        var message = msg;
        connection.invoke("SendMsg", message, connection).catch(function (err) {
            return console.error(err.toString());
        });

        var li = "<li>\
            <p class='time-p'></p>\
             <p class='msg-p-send'>" + message + "</p>\
            </li> ";
        document.getElementById("messagesList").innerHTML += li;
        event.preventDefault();
    });


}